package com.dhf.xhb.util;

import java.sql.*;
import java.util.List;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtil {
	private static ComboPooledDataSource dataSource = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	private Connection conn = null;
	static{
		try {
			dataSource = new ComboPooledDataSource("xhb");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("dbcp.properties加载，解析失败");
		}
	}
	public void getconn()
	{
		try {
			this.conn = dataSource.getConnection();
			this.conn.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("获取连接失败");
		}
	}
	public void getps(String sql)
	{
		this.getconn();
		try {
			this.ps = this.conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("获取预状态通道失败");
		}
	}
	public void bindParams(List<Object> params)
	{
		if(params!=null)
		{
			for(int i = 0;i<params.size();i++)
			{
				try {
					this.ps.setObject(i+1, params.get(i));
				} catch (SQLException e) {
					e.printStackTrace();
					System.out.println("JdbcUtil bindParams()绑定参数失败");
				}
				
			}
		}
	}
	public boolean updateByPs(String sql,List<Object> params)
	{
		this.getps(sql);
		this.bindParams(params);
		try {
			if(this.ps.executeUpdate()>0)
			{
				this.conn.commit();
				return true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("JdbcUtil updateByPs()方法增删改失败");
		} 
		return false;
	}
	public ResultSet queryByPs(String sql,List<Object> params)
	{
		this.getps(sql);
		this.bindParams(params);
		this.rs = null;
		try {
			rs = this.ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("JdbcUtil queryByPs()查询失败");
		}
		return rs;
	}
	
	public void closeResource()
	{
		try {
			if(rs!=null)
			{
				rs.close();
			}
			if(ps!=null)
			{
				ps.close();
			}
			if(conn!=null)
			{
				conn.close();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("关闭资源失败");
		}
	}
	
	public PreparedStatement getPs()
	{
		return this.ps;
	}
}
